package com.heima.search.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.SearchArticleVo;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 基本搜索业务
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
       //TODO
        //从es中获取数据
        SearchRequest request = new SearchRequest("article");
        String searchWords = dto.getSearchWords();
        if (searchWords == null || "".equals(searchWords)) {
            request.source().query(QueryBuilders.matchAllQuery());

        } else {
            request.source().query(QueryBuilders.matchQuery("all", searchWords));
            request.source().highlighter(new HighlightBuilder()
                    .field("title").
                    requireFieldMatch(false)
                    .preTags("<span style='color: red;font-size:inherit;'>")//高亮标红标签
                    .postTags("</span>"));
        }

        int num = dto.getPageNum();
        int size = dto.getPageSize();
        if (num !=0){
            request.source().from((num - 1) * size).size(size);
        }

        List<SearchArticleVo> searchArticleVoList=new ArrayList<>();
        // 3.发送请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            SearchHits searchHits = response.getHits();
            // 4.1.获取总条数
            long total = searchHits.getTotalHits().value;
            // 4.2.文档数组
            SearchHit[] hits = searchHits.getHits();

            for (SearchHit hit : hits) {
                // 获取文档source
                String json = hit.getSourceAsString();
                // 反序列化
                SearchArticleVo searchArticleVo = JSON.parseObject(json, SearchArticleVo.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    // 根据字段名获取高亮结果
                    HighlightField highlightField = highlightFields.get("title");
                    if (highlightField!=null){
                        String title = highlightField.getFragments()[0].string();
                        searchArticleVo.setH_title(title);
                    }
                }
                searchArticleVoList.add(searchArticleVo);
            }
        } catch (IOException e) {
            return ResponseResult.errorResult(501,"参数失效");
        }

        return ResponseResult.okResult(searchArticleVoList);


    }



    /**
     * 自动补全功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(UserSearchDto dto) {
       //TODO
        return null;
    }
}
